package ru.efimmatytsin.tweeterella;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.efimmatytsin.tweeterella.entities.User;
import ru.efimmatytsin.tweeterella.holders.UserInformationModelHolder;
import ru.efimmatytsin.tweeterella.services.UserService;
import ru.efimmatytsin.tweeterella.validators.LoginFormValidator;
import ru.efimmatytsin.tweeterella.viewmodels.LoginFormViewModel;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Efim Matytsin on 22.02.15.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserInformationModelHolder userInformationModelHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private LoginFormValidator loginFormValidator;

    @RequestMapping(method = RequestMethod.GET)
    public String initializeView(Model model) {
        if(userInformationModelHolder.getUser()!=null){
            return "redirect:/profile";
        }
        model.addAttribute("loginData",new LoginFormViewModel());
        return "login";
    }
    @RequestMapping(method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("loginData") LoginFormViewModel loginFormViewModel,
                             BindingResult bindingResult,
                             ModelMap model,HttpServletRequest request){
        loginFormValidator.validate(loginFormViewModel,bindingResult);
        if (!bindingResult.hasErrors()) {
            User user = userService.getUser(loginFormViewModel.getUsername(), User.class);
            if (user != null && user.getPassword().equals(loginFormViewModel.getPassword())) {
                userInformationModelHolder.setUser(user);
                return "redirect:/profile/id"+user.getId().toString();
            }
        }
        return "login";
    }
}
